﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace AutoStar
{
    public partial class DijalogGrad : Form
    {
        private Form1 parent;
        public DijalogGrad()
        {
            InitializeComponent();
        }
        public DijalogGrad(ref Form1 parent)
        {
            this.parent = parent;
            InitializeComponent();
        }

        private void btnDodaj_Click(object sender, EventArgs e)
        {
            try
            {
                MySqlConnection conn = ConnectionPool.checkOutConnection();
                AutoStarBaza ctx = new AutoStarBaza(conn);
                var upit2 = from d1 in ctx.mjesto where d1.naziv == tbNaziv.Text select d1;
                if (upit2.Count()!=0)
                {
                    MessageBox.Show("Vec postoji mjesto na istim nazivom u bazi...", "Obavjestenje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                    ConnectionPool.checkInConnection(conn);
                    return;
                }
                mjesto t = new mjesto();
                int a= Convert.ToInt32(mtbBrojPoste.Text);
                t.brojPoste = Convert.ToString(a);
                t.naziv = tbNaziv.Text;
                var upit3 = from d2 in ctx.drzava where d2.naziv == tbDrzava.Text select d2;
                if (upit3.Count() == 0)
                {
                    drzava z = new drzava();
                    z.naziv = tbDrzava.Text;
                    ctx.drzava.InsertOnSubmit(z);
                    ctx.SubmitChanges();
                    var upit = from s in ctx.drzava where s.naziv == tbDrzava.Text select s;
                    var m = upit.First();
                    t.drzavaid = m.id;
                }
                else
                {
                    var b = upit3.First();
                    t.drzavaid = b.id;
                }
                
                ctx.mjesto.InsertOnSubmit(t);
                ctx.SubmitChanges();
                var upit1 = from s1 in ctx.mjesto select s1;
                int index=upit1.Count()-1;
                ConnectionPool.checkInConnection(conn);
                parent.popuniKomboMjesto(index);
                this.Close();
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Nije moguce povezati se sa bazom podataka. Program ce se zavrsiti. Detalji: " + ex.Message, "Problem u ucitavanju baze podataka", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
            finally { }
        }
    }
}
